package yxy.game.pm2.bean.sdk;

import java.util.ArrayList;
import java.util.List;
import org.redisson.api.RList;
import yxy.apple.util.redisson.RedisException;
import yxy.cherry.game.base.redis.RedisManager;
import yxy.game.pm2.bean.module.BaseGameRedisBean;

/**
 * 渠道控制 允许redis里有的渠道登陆
 * subchannel 为 channel 时，即channel与允许所有大渠道为channel登陆
 * @author Dell
 *
 */
public class ChannelControl extends BaseGameRedisBean{

	// bean===========================================================================

	private String csstr;	//channel + "-" + subchannel           大渠道-小渠道
	
	public String getCsstr() {
		return csstr;
	}
	public void setCsstr(String csstr) {
		this.csstr = csstr;
	}


	// func==========================================================================

	public static int addsuccess = 1;	
	public static int addfail = 2;	
	public static int alreadyexists = 3;	
	
	/**
	 * 是否可以登陆
	 * @param channel
	 * @param subchannel
	 * @return
	 */
	public static boolean canlogin(String channel, String subchannel) {
		List<String> list = ChannelControl.all();
		if(list == null || list.size() == 0) {
			return false;
		}
		
		String key1 = channel + "-" + subchannel;
		String key2 = channel + "-" + channel;
		if(list.contains(key1) || list.contains(key2)) {
			return true;
		}
		
		return false;
	}

	/**
	 * 添加可登录渠道
	 * @param channel
	 * @param subchannel
	 * @return
	 */
	public static int addcanlogin(String channel, String subchannel) {
		List<String> list = ChannelControl.all();

		String key1 = channel + "-" + subchannel;
		String key2 = channel + "-" + channel;
		if(list.contains(key1) || list.contains(key2)) {
			return alreadyexists;
		}
		
		try {
			ChannelControl.touch().add(key1);
		} catch (RedisException e) {
			e.printStackTrace();
			return addfail;
		}
		
		return addsuccess;
	}
	
	// redis==========================================================================
	
	static public String key() {
		return "SDK:CHANNELCONTROL";
	}

	static public RList<String> touch() throws RedisException {
		return RedisManager.client(redis()).getList(key());
	}

	static public List<String> all() {
		try {
			List<String> list = touch().readAll();
			return list;
		} catch (RedisException e) {
		}
		return new ArrayList<String>();
	}
	

	// lock==========================================================================

	@Override
	public String lockKey() {
		return String.format("lock:%s", key());
	}
}
